const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV   
})
const axios = require('axios');
const TimeUtil = require('../timeutil');  
const getKxJscxHandler = require('./handler');
const dayjs = require('dayjs');
const USER = 'edu-cloud-users'
const db = cloud.database()
exports.main = async (event, context) => {
  /**初始化请求接口 */
  var EDU_API = 'http://jwgl.sdust.edu.cn/app.do?method=getKxJscx&time=#{time}&idleTime=#{idleTime}'
  /** 获取查询日期 */
  let date = event.date || TimeUtil.TimeCodeYmd()
  EDU_API = EDU_API.replace('#{time}', date);
  /**获取查询时间段 */
  let idleTime = event.idleTime
  EDU_API = EDU_API.replace('#{idleTime}', idleTime);
  console.log(EDU_API)
  /** 是否对返回结果预处理 */
  let resHandle = event.resHandle || false
  /** 获取OPENID */
  const wxContext = cloud.getWXContext()
  /**openid 冗余获取形式 */
  let openid = event.openid || wxContext.OPENID;
  // console.log(openid)
  /** 获取TOKEN */
  let token = '';
  let userBase = {}
  console.log('OPENID : '+openid)
  let queryRes = await db.collection(USER).where({
    openid
  }).get();
  if (queryRes.data.length == 0) {
    return {
      errCode: -1,
      errMsg: '未绑定学号信息'
    }
  } else {
    userBase = queryRes.data[0];
    token = userBase.token;
    /** 替换请求参数 */
    // EDU_API = EDU_API.replace('#{xh}', userBase.bindId);
  }
  
  console.log('请求地址为')
  console.log(EDU_API)
  let reqRes = await axios({
    method: "GET",
    url: EDU_API,
    headers: {
      "content-type": "application/json;charset=utf-8",
      "User-Agent": "Mozilla/5.0 (Linux; U; Mobile; Android 6.0.1;C107-9 Build/FRF91 )",
      "cache-control": "max-age=0",
      "token": token
    }
  })
  // console.log(reqRes)
  
  if(reqRes.data.token == -1){
    //TOKEN 过期
    console.log('--更新TOKEN--')
    let authRes = await cloud.callFunction({
      name:'edu-token-center',
      data:{
        action:'flushToken',
        openid:openid
      }
    })
    if(authRes.result.errCode == -1){
      return authRes.result
    }
    reqRes = await axios({
      method: "GET",
      url: EDU_API,
      headers: {
        "content-type": "application/json;charset=utf-8",
        "User-Agent": "Mozilla/5.0 (Linux; U; Mobile; Android 6.0.1;C107-9 Build/FRF91 )",
        "cache-control": "max-age=0",
        "token": authRes.result.data.token
      }
    })
  }
  let res =  {
    status: reqRes.status,
    data: reqRes.data
  };
  /** 数据预处理 */
  if(resHandle){
    return await getKxJscxHandler.main(res);
  }else{
    return res;
  }
}
